package java_learn.java_jinjie.DataStructure;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: 李浩然
 * @Date: 2020/12/4 11:03 下午
 * HashMap存储自定义类型键值
 * Map集合保证key是唯一的:
 * 作为key的元素,必须重写hashCode方法和equals方法,以保证key唯一
 */
public class DemoHashMapSavePerson {
    public static void main(String[] args) {
//        Demo01();
        Demo02();
    }

    private static void Demo02() {
        HashMap<Person, String> map = new HashMap<>();
        map.put(new Person("女王", 18), "england");
        map.put(new Person("始皇帝", 18), "秦国");
        map.put(new Person("普京", 18), "俄罗斯");
        map.put(new Person("女王", 18), "france");
        for (Map.Entry<Person, String> entry : map.entrySet()) {
            System.out.println(entry.getKey() + "-" + entry.getValue());
        }
    }

    /**
     * HashMap存储自定义类型键值
     * key:Person类型
     * Person类就必须重写hashCode方法和equals方法,以保证key唯一
     * value:String类型
     * 可以重复
     */
    private static void Demo01() {
        HashMap<String, Person> map = new HashMap<>();
        map.put("beijing", new Person("张三", 18));
        map.put("beijing", new Person("李三", 18));
        map.put("beijing2", new Person("张三", 19));
        map.put("beijing3", new Person("张三", 15));
        map.put("beijing4", new Person("张三", 16));
        System.out.println(map);
        for (Map.Entry<String, Person> entry : map.entrySet()) {
            System.out.println(entry.getKey() + entry.getValue());
        }
    }
}
